/*
 * args.c
 *
 *  Created on: 2015??12??23??
 *      Author: yuguo.wang
 */
#include <string.h>

#include "args.h"
#include "public_lib.h"

/*
 * Split string to argc and argvs.
 * '#' is comment flag
 * '$' is repeat flag, it's followed by a number which indicates repeat times.
 * '$' only happens at the last parameter.
 */
int str_to_args(char *str, args_t *args)
{
    int i;
    int argc=0;
    int start=0;

    /* '#' is comment flag */
    for(i=0;str[i] && str[i]!='#';i++)
    {
        if(str[i]!=' ' && str[i]!='\t')
        {
            if(!start)
            {
                args->argv[argc] = &str[i];
            }
            start++;
        }
        else
        {
            if(start)
            {
                argc++;
                str[i] = '\0';
                start = 0;
                if(argc >= ARGS_MAX_ARGV)
                {
                    args->argc = argc;
                    return -1;
                }
            }

        }
    }
    args->argc = argc + (start?1:0);

    if(!args->argc)
        return -1;

    // check if the command needs repeat
    if(args->argv[args->argc-1][0] == '$')
    {
        args->argc--;
        args->repeate = str_to_val(args->argv[args->argc]+1);
    }
    else
        args->repeate = 1;
    return 0;
}


int args_to_str(int argc, char *argv[], char *str, int len)
{
    int i;
    int j = 0;
    int k = 0;
    for(i=0;i<argc;i++)
    {
        while(argv[i][j])
        {
            if(k<len-1)
                str[k++] = argv[i][j++];
            else
            {
                str[k] = 0;
                return -1;
            }
        }

        /* append space between arguments */
        if(k<len-1)
            str[k++] = ' ';
        else
        {
            str[k] = 0;
            return -1;
        }

        j=0;
    }
    str[k] = 0;
    return 0;
}



